package cn.puge.usercenter.controller;


import cn.puge.commonutils.R;
import cn.puge.servicebase.exceptionhandler.PuGeiException;
import cn.puge.usercenter.entity.PugeUserLogin;
import cn.puge.usercenter.service.PugeUserLoginService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 *  前端控制器
 * </p>
 * 用户登录
 * @author LIJW
 * @since 2020-09-28
 */
@RestController
@RequestMapping("/usercenter/puge-user-login")
@CrossOrigin
public class PugeUserLoginController {

    @Autowired
    private PugeUserLoginService pugeUserLoginService;
    /**
     * 登录验证
     * @return
     */
    @PostMapping("userLogin")
    public R userLogin(@RequestBody PugeUserLogin pugeUserLogin){


        //获取主体对象
        Subject subject = SecurityUtils.getSubject();


        try{
            subject.login(new UsernamePasswordToken(pugeUserLogin.getUsername(),pugeUserLogin.getPassword()));
        }catch (UnknownAccountException e){
            throw new PuGeiException(20001,"用户名错误");
        }catch (IncorrectCredentialsException e){
            throw new PuGeiException(20001,"密码错误");
        }

        return R.ok().message("登录成功");
    }

    /**
     * 注册账号
     */
    @PostMapping("userRegister")
    public R register(@RequestBody PugeUserLogin pugeUserLogin){
        pugeUserLoginService.UserRegister(pugeUserLogin);
        return R.ok();
    }







}

